package com.bbmc.bttemp;

import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.bbmc.bttemp.AAChartCoreLib.AAChartConfiger.AAChartModel;
import com.bbmc.bttemp.AAChartCoreLib.AAChartConfiger.AAChartView;
import com.bbmc.bttemp.AAChartCoreLib.AAChartConfiger.AAOptionsConstructor;
import com.bbmc.bttemp.AAChartCoreLib.AAChartConfiger.AASeriesElement;
import com.bbmc.bttemp.AAChartCoreLib.AAChartConfiger.PointD;
import com.bbmc.bttemp.AAChartCoreLib.AAChartEnum.AAChartLineDashStyleType;
import com.bbmc.bttemp.AAChartCoreLib.AAChartEnum.AAChartType;
import com.bbmc.bttemp.AAChartCoreLib.AAOptionsModel.AALabel;
import com.bbmc.bttemp.AAChartCoreLib.AAOptionsModel.AAOptions;
import com.bbmc.bttemp.AAChartCoreLib.AAOptionsModel.AAStyle;
import com.bbmc.bttemp.AAChartCoreLib.AAOptionsModel.AAYAxis;
import com.bbmc.bttemp.AAChartCoreLib.AAOptionsModel.AAPlotLinesElement;
import com.bbmc.bttemp.untils.BluetoothUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import www.linwg.org.lib.LCardView;


public class MainActivity extends AppCompatActivity {

    private AAChartView aaChartView;
    private static final String TAG = "TAG";
    protected static final int RECEICED = 0;
    private BluetoothUtils btu;
    private TextView tvTmp;
    private TextView tvTip;
    private LCardView ovalcard;
    List<PointD> numberArr;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);
        repeatUpdateChartData();
        numberArr = new ArrayList<PointD>();

        tvTmp = (TextView) findViewById(R.id.tv_tmp);
        tvTip = findViewById(R.id.tv_tip);
        ovalcard = findViewById(R.id.ovalcard);

        Intent intent = getIntent();
        String chartType = intent.getStringExtra("chartType");  //建立折线图
        AAOptions aaOptions = configureTheChartOptions(chartType);
        aaChartView = findViewById(R.id.AAChartView);
        aaChartView.aa_drawChartWithChartOptions(aaOptions);
    }

/*
*  增加温度文字随温度区间改变而改变颜色功能
* */
    private  Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case RECEICED:

                        double tmp = (Double) msg.obj;
                        tvTmp.setText(String.format(tmp + "℃", "%.1f"));// 温度数字配置
                        if ( tmp >= 30f && tmp < 36.7f ) { //5AD0CF图标绿   04d69f正常绿  61A0F3主题蓝  ffd066橙  ef476f红  94BDF3浅蓝
                            tvTmp.setTextColor(Color.parseColor("#61A0F3"));
                            tvTip.setText("温度偏低");
                            tvTip.setTextColor(Color.parseColor("#61A0F3"));
                            ovalcard.setShadowColor(Color.parseColor(("#61A0F3")));
                        }else if ( tmp >= 36.7f && tmp <= 37.2f ) {
                            tvTmp.setTextColor(Color.parseColor("#5AD0CF"));
                            tvTip.setText("体温正常");
                            tvTip.setTextColor(Color.parseColor("#5AD0CF"));
                            ovalcard.setShadowColor(Color.parseColor(("#5AD0CF")));
                        }else if (tmp > 37.2f && tmp < 45f ) {
                            tvTmp.setTextColor(Color.parseColor("#ef476f"));
                            tvTip.setText("体温异常");
                            tvTip.setTextColor(Color.parseColor("#ef476f"));
                            ovalcard.setShadowColor(Color.parseColor(("#ef476f")));
                        }else {
                            tvTmp.setTextColor(Color.parseColor("#94BDF3"));
                            tvTip.setText("温度偏低");
                            tvTip.setTextColor(Color.parseColor("#94BDF3"));
                            ovalcard.setShadowColor(Color.parseColor("#94BDF3"));
                        }
                    numberArr.add(new PointD(tmp));

                    //   numberArr.add(new PointD(tmp));

                    break;

                default:
                    break;
            }
        }

    };


    private AAOptions configureTheChartOptions(String chartType) {  //返回折线图类型
        if (chartType!=null) {
            return configureAAPlotLinesForChart();
        }
        return configureAAPlotLinesForChart();
    }


    private AAOptions configureAAPlotLinesForChart() {  //配置折线图格式

        AASeriesElement[] aaSeriesElementsArr = configureChartSeriesArray();

        AAChartModel aaChartModel = new  AAChartModel()
                .title("历史记录")
                .titleFontWeight("regular")
                .yAxisTitle("")
                .xAxisTickInterval(5)  //x轴间隔数
                .yAxisTickInterval(2) //y轴间隔数
                .yAxisMin(25f)
                .yAxisMax(43f)
                .chartType(AAChartType.Areaspline)//图形类型
                .dataLabelsEnabled(false)
                .series(aaSeriesElementsArr);

        AAOptions aaOptions = AAOptionsConstructor.configureChartOptions(aaChartModel);

        //5AD0CF图标绿   04d69f正常绿  61A0F3主题蓝  ffd066橙  ef476f红  94BDF3浅蓝
        AAPlotLinesElement[] aaPlotLinesElementsArr = {     //横向分割线及弹窗样式
                new AAPlotLinesElement()
                        .color("#61A0F3")//颜色值(16进制)
                        .dashStyle(AAChartLineDashStyleType.LongDashDotDot)//样式：Dash,Dot,Solid等,默认Solid
                        .width((0.5f)) //标示线粗细
                        .value((30f)) //所在位置
                        .zIndex((1)) //层叠,标示线在图表中显示的层叠级别，值越大，显示越向前
                        .label(new AALabel()
                        .style(new AAStyle()
                                .color("#1e90ff")
                                .fontWeight("bold")
                        )
                )
                ,
                new AAPlotLinesElement()
                        .color("#5AD0CF")//颜色值(16进制)1e90ff
                        .dashStyle(AAChartLineDashStyleType.LongDashDot)//样式：Dash,Dot,Solid等,默认Solid
                        .width((0.5f)) //标示线粗细
                        .value((36.7f)) //所在位置
                        .zIndex((1)) //层叠,标示线在图表中显示的层叠级别，值越大，显示越向前
                        .label(new AALabel()
                        .style(new AAStyle()
                                .color("#ef476f")
                                .fontWeight("bold")
                        )
                )
                ,
                new AAPlotLinesElement()
                        .color("#ef476f")//颜色值(16进制)
                        .dashStyle(AAChartLineDashStyleType.LongDash)//样式：Dash,Dot,Solid等,默认Solid
                        .width((0.5f)) //标示线粗细
                        .value((37.2f)) //所在位置
                        .zIndex((1)) //层叠,标示线在图表中显示的层叠级别，值越大，显示越向前
                        .label(new AALabel()
                        .style(new AAStyle()
                                .color("#04d69f")
                                .fontWeight("bold")
                        )
                )
                ,
        };

        AAYAxis aaYAxis =  aaOptions.yAxis;
        aaYAxis.plotLines(aaPlotLinesElementsArr);

        return aaOptions;
    }

    private AASeriesElement[] configureChartSeriesArray() {




        Map map1 = new HashMap();  //设置温度分割区 暂时以30  36.7  37.2 为温度界线  不同区域颜色不同
        map1.put("value",30);
        map1.put("color","#94BDF3");//5AD0CF图标绿   04d69f正常绿  61A0F3主题蓝  ffd066橙  ef476f红 94BDF3浅蓝
        Map map2 = new HashMap();
        map2.put("value",36.7);
        map2.put("color","#61A0F3");
        Map map3 = new HashMap();
        map3.put("value",37.2);
        map3.put("color","#5AD0CF");
        Map map4 = new HashMap();
        map4.put("color","#ef476f");
        Map[] zonesArr = new Map[]{map1,map2,map3,map4};

        AASeriesElement[] aaSeriesElementsArr = new AASeriesElement[]{
                new AASeriesElement()
                        .color("#61A0F3")
                        .name("温度℃")
                        .data(numberArr)
                        .fillOpacity(0.5f)
                        .zones(zonesArr)
                        .lineWidth(2f),
        };

        return aaSeriesElementsArr;
    }

    void repeatUpdateChartData() {
        final Handler mHandler = new Handler();
        Runnable r = new Runnable() {
            @Override
            public void run() {
                AASeriesElement[] aaSeriesElementsArr = configureChartSeriesArray();
                aaChartView.aa_onlyRefreshTheChartDataWithChartOptionsSeriesArray(aaSeriesElementsArr);

                //每隔1s循环执行run方法
                mHandler.postDelayed(this, 1000);
            }
        };

        mHandler.postDelayed(r, 10);//延时10毫秒
    }

    @Override
    protected void onDestroy() {

        try {
            if (btu != null)
                btu.close();
        } catch (IOException e) {

            e.printStackTrace();
        }
        super.onDestroy();
    }

    private void initBluetooth() {
        try {
            btu = BluetoothUtils.initBluetoothUtils();
            // 注册事件
            btu.setOnBluetoothReadable(new BluetoothUtils.OnBluetoothReadable() {

                @Override
                public void read(BluetoothDevice bluetoothDevice, String result, InputStream is) {
                    // 以16进制数据接收
                    byte[] buffer = new byte[1024];
                    try {
                        int len = is.read(buffer);
                        // Log.i(TAG, "读取字节长度=" + len);
                        double tmp = (250 + Double.parseDouble(buffer[0] + "")) / 10; // 获取当前温度

                        Message msg = new Message();
                        msg.what = RECEICED;
                        msg.obj = tmp;
                        handler.sendMessage(msg);

                        Log.i(TAG, "当前的温度=" + tmp);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });

            String deviceName = btu.getBluetoothDeviceName();
            Log.i(TAG, deviceName);
        } catch (BluetoothUtils.BluetoothDisableException e) {
            // 蓝牙不可用
            Toast.makeText(this, "蓝牙设备不可用", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (BluetoothUtils.BluetoothNoDeivceException e) {
            Toast.makeText(this, "无连接设备", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        } catch (IOException e) {
            Toast.makeText(this, "连接出错", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {

        super.onResume();
        initBluetooth();
    }

}
